package com.zxkj.domain.mapper;

import com.zxkj.domain.entity.Addr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Administrator on 2017/10/11.
 */
@Service
public class AddrServiceImpl implements AddrService {

    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Addr> getAllAddr() {
        StringBuilder sb = new StringBuilder();
        sb.append("select * from addr");
        return jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper(Addr.class));
    }

    @Override
    public List<Addr> getAllAddrGtZero() {
        StringBuilder sb = new StringBuilder();
        sb.append("select * from addr where corp_id > 0");
        return jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper(Addr.class));
    }

    @Override
    public Addr getAddrFromNoCorpId() {
        StringBuilder sb = new StringBuilder();
        sb.append("select * from addr WHERE corp_id=0 LIMIT 1;");
        return jdbcTemplate.queryForObject(sb.toString(), new RowMapper<Addr>() {
            @Override
            public Addr mapRow(ResultSet rs, int rowNum) throws SQLException {

                Addr addr  = new Addr();
                addr.setCorpId(rs.getInt("corp_id"));
                addr.setEnhancedName(rs.getString("EnhancedName"));
                return addr;
            }
        });
    }

    @Override
    public int updateCorpIdByEnhancedName(String EnhancedName,int corp_id) {
        StringBuilder sb = new StringBuilder();
        sb.append("update addr set corp_id=? WHERE EnhancedName=?;");
        return jdbcTemplate.update(sb.toString(),corp_id,EnhancedName);
    }
}
